package dome_001;

/**
 * <p>Description: [死锁]</p>
 * Created on 2020/12/2
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Demo001_01 {

    public static void main(String[] args) {
        Obj1 obj1 = new Obj1();
        Obj2 obj2 = new Obj2();

        Thread thread1 = new Thread(new SyncAddRunnable(obj1, obj2, 1, 2, true));
        Thread thread2 = new Thread(new SyncAddRunnable(obj1, obj2, 1, 2, false));

        thread1.setName("thread1");
        thread2.setName("thread2");

        thread1.start();
        thread2.start();
    }

    public static class SyncAddRunnable implements Runnable {
        Obj1 obj1;
        Obj2 obj2;
        int a;
        int b;
        boolean flag;

        public SyncAddRunnable(Obj1 obj1, Obj2 obj2, int a, int b, boolean flag) {
            this.obj1 = obj1;
            this.obj2 = obj2;
            this.a = a;
            this.b = b;
            this.flag = flag;
        }

        @Override
        public void run() {
            System.out.println(String.format("运行线程开始"));
            try {
                if (flag) {
                    synchronized (obj1){
                        System.out.println(obj1 + "已锁");
                        Thread.sleep(100L);
                        synchronized (obj2){
                            System.out.println(obj2 + "已锁");
                            System.out.println(obj1 + "-" + obj2 + "-" + a + "-" + b + "-" + flag);
                        }
                    }
                } else {
                    synchronized (obj2){
                        System.out.println(obj2 + "已锁");
                        Thread.sleep(100L);
                        synchronized (obj1){
                            System.out.println(obj1 + "已锁");
                            System.out.println(obj1 + "-" + obj2 + "-" + a + "-" + b + "-" + flag);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(String.format("运行线程结束"));
        }
    }

    public static class Obj1 {
    }

    public static class Obj2 {
    }
}
